<?php
namespace app\base\controller;

use think\Controller;
use think\Db;
use think\exception\HttpResponseException;
use think\Response;

class BaseCtrl extends Controller
{
    protected $get;
    protected $post;
    protected $host;
    protected $route;
    /**
     * 初始化参数
     */
    protected function _initialize()
    {
        $this->get   = $this->request->get();
        $this->post  = $this->request->post();
        $this->host  = $this->request->server('REQUEST_SCHEME') . '://' . $this->request->host();
        $this->route = '/' . $this->request->module() . '/' . hump_underline($this->request->controller()) . '/' . $this->request->action();
    }
    /**
     * 获取表字段及其默认值
     * @param  string $tn 表名，不含前缀
     * @return array
     */
    protected function table_fields($tn)
    {
        $column = Db::query('SELECT COLUMN_NAME,COLUMN_DEFAULT FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = "' . config('database.database') . '" AND TABLE_NAME = "' . config('database.prefix') . $tn . '"');
        $data   = [];
        foreach ($column as $k => $v) {
            $data[$v['COLUMN_NAME']] = is_null($v['COLUMN_DEFAULT']) ? '' : $v['COLUMN_DEFAULT'];
        }
        return $data;
    }
    /**
     * 返回API
     * @access protected
     * @param  string  $msg    提示信息
     * @param  integer $code   状态码
     * @param  array   $data   对应数据
     * @param  array   $extend 扩展字段
     * @param  array   $header HTTP头信息
     * @return void
     * @throws HttpResponseException
     */
    protected function returnAPI($msg = '', $code = 1, $data = [], $extend = [], $header = [])
    {
        $return = [
            'msg'  => $msg,
            'code' => $code,
        ];
        if (!empty($data)) {
            $return['data'] = $data;
        }
        if (!empty($extend)) {
            foreach ($extend as $k => $v) {
                $return[$k] = $v;
            }
        }
        $response = Response::create($return, 'json')->header($header);
        throw new HttpResponseException($response);
    }
}
